package com.mrxu.monitor.notice;

import com.mrxu.monitor.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@EnableAsync
public class MessageCenterService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private List<NotifyService> notifyList;

    @Async("MessageCenterServiceExecutorService")
    public void sendNoticeMsg(String content,NoticeType type) {
        boolean notExist = redisTemplate.opsForValue().setIfAbsent(RedisConstant.getKey("NoticeMsg",type.name()),"1",30, TimeUnit.SECONDS);
        if(notExist) {
            for(NotifyService temp : notifyList) {
                try {
                    temp.sendMsg(content);
                }
                catch (Exception e) {
                    log.error("发送通知异常:{}",e);
                }
            }
        }
    }

    @Async("MessageCenterServiceExecutorService")
    public void sendNoticeMsg(String content,String errorCode) {
        boolean notExist = redisTemplate.opsForValue().setIfAbsent(RedisConstant.getKey("NoticeMsg",errorCode),"1",30, TimeUnit.SECONDS);
        if(notExist) {
            for(NotifyService temp : notifyList) {
                try {
                    temp.sendMsg(content);
                }
                catch (Exception e) {
                    log.error("发送通知异常:{}",e);
                }
            }
        }
    }

    @Bean("MessageCenterServiceExecutorService")
    public ExecutorService executor() {
        return Executors.newSingleThreadExecutor();
    }



}
